<?php

class Controller_Upload extends Controller_Website {

    public function action_ajaxadd() {
        $file = $_FILES['file'];
        if (!Upload::valid($file)) {
            $ret = array('status' => 'error', 'msg' => '不是有效的文件');
            echo json_encode($ret, JSON_UNESCAPED_UNICODE);
            exit;
        } elseif (!Upload::not_empty($file)) {
            $ret = array('status' => 'error','msg' => '上传文件为空');
            echo json_encode($ret, JSON_UNESCAPED_UNICODE);
            exit;
        } elseif (!Upload::type($file, array('jpg', 'png'))) {
            $ret = array('status' => 'error','msg' => '文件格式只能为jpg,png');
            echo json_encode($ret, JSON_UNESCAPED_UNICODE);
            exit;
        } elseif (!Upload::size($file, '1M')) {
            $ret = array('status' => 'error','msg' => '文件大小不能超过1M');
            echo json_encode($ret, JSON_UNESCAPED_UNICODE);
            exit;
        }
        
        $type = Arr::get($_GET, 'type', 'news_image');
        $result = $this->_add($file, $type);
        if ($result !== false) {
            $ret = array('status' => 'ok','data' => $result);
        } else {
            $ret = array('status' => 'error','msg' => '未知错误');
        }
        
        header('Content-Type: application/json; charset=utf-8');
        echo json_encode($ret, JSON_UNESCAPED_UNICODE);
        exit;
    }
    
    public function action_add() {
        $img_url = Arr::get($_GET, 'img_url');
        $file_size = Arr::get($_GET, 'file_size');
        $img_width = Arr::get($_GET, 'img_width');
        $img_height = Arr::get($_GET, 'img_height');
        if (!empty($img_url)) {
            $file_type = explode('.', $img_url);
            $data = array(
                'img_source' => 'aliyun',
                'user_id' => $this->user['id'],
                'user_name' => $this->user['username'],
                'file_src' => $img_url,
                'file_type' => end($file_type),
                'file_size' => $file_size,
                'img_width' => $img_width,
                'img_height' => $img_height,
                'add_time' => strtotime('now'),
            );
            $uploadModel = Model::factory('articlePic');
            $uploadModel->insert($data);
        }
    }
    
    public function action_grid() {
        $img_source = Arr::get($_GET, 's');
        
        $where = array();
        $where['user_id'] = $this->user['id'];
        if ($img_source == 'weixin') {
            $where['img_source'] = 'weixin';
        } else {
            $where['img_source'] = 'aliyun';
        }
        $where['ORDER'] = 'id DESC';
        $q = Arr::get($_GET, 'q', '');
        if (!empty($q)) {
            $where['file_src'] = array('like'=>"%$q%");
        }
    
        $m_upload = Model::factory('articlePic');
        $total = $m_upload->count($where);
        $pager = new Pager($total, 20);
        $list = $m_upload->select($pager->offset, $pager->size, $where)->as_array();

        if ($this->auto_render !== TRUE) {
            $this->content = View::factory('upload/grid_incr');
            $this->content->list = $list;
            $nexturl = '';
            if ($pager->next_page) {
                $nexturl = $pager->url($pager->next_page);
            }
            header('Content-Type: application/json; charset=utf-8');
            $ret = array(
                'content'=>(string)$this->content, 
                'nexturl'=>$nexturl, 
            );
            echo json_encode($ret);
            exit;
        } else {
            if ($img_source == 'weixin') {
                $this->content = View::factory('upload/grid_wx');
            } else {
                $this->content = View::factory('upload/grid');
            }
        }
    
        $this->content->list = $list;
        $this->content->pager = $pager;
        
        echo $this->content;exit;
    }

    protected function _add($file, $type="add_material") {
        $file_type = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
        $filename = strtotime('now').str_pad(mt_rand(1, 9999), 4, '0', STR_PAD_LEFT) . '.' . $file_type;
        $sub_directory = date('Ymd');
        
        $directory = '/tmp/wxnews';
        $upload_dir = $directory.DIRECTORY_SEPARATOR.$sub_directory;
        if (!is_dir($upload_dir)) {
            mkdir($upload_dir, 0755, TRUE);
        }
        if (!is_writable($upload_dir)) {
            chmod($upload_dir, 0755);
        }
        
        $file_path = Upload::save($file, $filename, $upload_dir);
        list($width, $height) = getimagesize($file_path);

        if (Kohana::$environment == Kohana::DEVELOPMENT) {
            $this->appid = 'wxc5b1d86df49a2dc4';
        } else {
            $this->appid = Arr::get($_GET, 'appid');
        }
        
        $wxconfig = Wxapp::getconfig();
        $wxconfig['app_id'] = $this->appid;
        $app = Wxapp::getapp($wxconfig);
        
        $material = $app->material;
        if ($type == 'add_material') {
            $result = $material->uploadImage($file_path);
        } else {
            $result = $material->uploadArticleImage($file_path);
        }

        $file_src = $result->url;
        $data = array(
            'img_source' => 'weixin',
            'user_id' => $this->user['id'],
            'user_name' => $this->user['username'],
            'file_type' => $file_type,
            'file_size' => $file['size'],
            'img_width' => $width,
            'img_height' => $height,
            'file_src' => $file_src,
            'add_time' => strtotime('now'),
        );
        $uploadModel = Model::factory('articlePic');
        $ret = $uploadModel->insert($data);
        if($ret !== false) {
            return $result;
        } else {
            return false;
        }
    }
    
}
